//
//  CarTeamViewController.m
//  阿帕
//
//  Created 阿帕 on 2019/12/28.
//  Copyright © 2019 GCY. All rights reserved.
// Invite drivers to join the list

#import "CarTeamViewController.h"

#import "SGPagingView.h"

#import "CarTeamCell.h"
#import "CarTeamTwoCell.h"

@interface CarTeamViewController ()<UITableViewDataSource, UITableViewDelegate, DriverBeInvitedRecordButtonDelegate, SGPageTitleViewDelegate>
{
    /**
     1 申请列表
     2 邀请列表
     */
    NSInteger _recordType;
}
@property (strong , nonatomic)UITextField *textFiled;

@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (strong , nonatomic)NSMutableArray *carTeamCodeArray;

@property (strong , nonatomic)UIImageView *foundImageView;

@property (strong , nonatomic)UIButton *confirmButton;

@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation CarTeamViewController

static const CGFloat cellHeight = 100;

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _pageNum = 1;
    
    _recordType = 1;//默认申请列表
    
    [self baseViewSetup];
}

- (void)baseViewSetup {
    
    self.view.backgroundColor = BackgroundColor;
    
    _textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 10, ScreenW, 40)];
    _textFiled.font = font(14);
    _textFiled.text = @"";
    _textFiled.backgroundColor = [UIColor whiteColor];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textFiled.keyboardType = UIKeyboardTypeDefault;
    _textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"车队名称/手机号/联系人" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, 40)];
    _textFiled.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 40)];
    _textFiled.leftViewMode = UITextFieldViewModeAlways;
    [_textFiled addSubview: leftView];
    
    
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenW-40, 10, 20, 20)];
    searchImage.userInteractionEnabled = YES;
    searchImage.image = [UIImage imageNamed:@"gcy_icon_search_siji"];
    _textFiled.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    _textFiled.rightViewMode = UITextFieldViewModeAlways;
    
    [searchImage nyl_addTapGes:^{
        _pageNum = 1;
        [self carTeamListRequest];
    }];
    [_textFiled addSubview:searchImage];
    
    
    NSArray *titleArr = @[@"申请加入", @"邀请记录"];
    SGPageTitleViewConfigure *configure = [SGPageTitleViewConfigure pageTitleViewConfigure];
    configure.indicatorStyle = SGIndicatorStyleCover;
    configure.indicatorColor = Theme_ColorValue;
    configure.titleColor = Theme_ColorValue;
    configure.indicatorHeight = SY(30);
    configure.indicatorAdditionalWidth = 120;
    configure.titleSelectedColor = [UIColor whiteColor];
    /// pageTitleView
    SGPageTitleView *pageTitleView = [SGPageTitleView pageTitleViewWithFrame:CGRectMake(0, 0, 270, 30) delegate:self titleNames:titleArr configure:configure];
    pageTitleView.layer.borderWidth = 1;
    pageTitleView.layer.borderColor = Theme_ColorValue.CGColor;
    pageTitleView.layer.cornerRadius = 3;
    pageTitleView.layer.masksToBounds = YES;
    pageTitleView.backgroundColor = [UIColor whiteColor];
    self.navigationItem.titleView = pageTitleView;
    
    
    [self.view addSubview:_textFiled];
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.confirmButton];
    
//    [self carTeamListRequest];
}


- (void)carTeamListRequest {
    WEAKSELF
    
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSString *urlString = @"";
    
    if (_recordType == 1) {
        urlString = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], DRIVER_APPLYTEAMLIST);
    } else {
        //需要变成基础服务的接口
        urlString = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], INVITEAPPLYRECORD_INVITELIST);
    }
    
    NSDictionary *params = @{
        @"pageSize":DEFULT_LOAD_NUM,
        @"pageNum":[NSNumber numberWithInteger:_pageNum],
        //        @"type": [NSNumber numberWithInteger:_recordType],//记录类型：1申请加入，2邀请加入
        @"searchInfo": _textFiled.text,
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
    };
    
    [HTTPManager getNetworkRequest:urlString withParameter:params withVC:self netName:@"车队/邀请记录列表" success:^(id response, NSString *msg) {
        
        if ([response[@"records"] count] != 0) {
            if (_recordType == 1) {
                [weakSelf.dataArray addObjectsFromArray:[CarTeamModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            } else {
                [weakSelf.dataArray addObjectsFromArray:[CarTeamInvitedRecordModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            }
            
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            
            weakSelf.foundImageView.hidden = YES;
            weakSelf.tableView.hidden = NO;
            
        }else{
            
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
                weakSelf.tableView.hidden = YES;
            }
            
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        
        [weakSelf.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)pageTitleView:(SGPageTitleView *)pageTitleView selectedIndex:(NSInteger)selectedIndex {
//    NSLog(@"seg.tag-->%ld",selectedIndex);
    
    _pageNum = 1;
    
    switch (selectedIndex) {
        case 0:
            _recordType = 1;
            self.tableView.frame = CGRectMake(0, 51, ScreenW, ScreenH - NavHeight - 51 - 75);
            self.confirmButton.hidden = NO;
            [self carTeamListRequest];
            break;
        case 1:
            _recordType = 2;
            self.tableView.frame = CGRectMake(0, 51, ScreenW, ScreenH - NavHeight - 51);
            self.confirmButton.hidden = YES;
            [self carTeamListRequest];
            break;
    }
    
    [self.tableView reloadData];
}

//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    [self carTeamListRequest];
}
- (void)loadMoreData{
    _pageNum ++;
    [self carTeamListRequest];
}

#pragma mark - 确认申请
- (void)confirmButtonClick {
    WEAKSELF
    
    if (self.carTeamCodeArray.count == 0) {
        [XSInfoView showInfo:@"请先选择车队" onView:self.view];
        return;
    }
    
    NSString *arrStr = [self.carTeamCodeArray componentsJoinedByString:@","];
    
    NSDictionary *parmas = @{@"teamCodes": arrStr, @"token":[UserDefaultUtil valueForKey:USER_TOKEN],};
    
    //需要变成基础服务的接口
    [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], INVITEAPPLYRECORD_BATCHAPPLY) withParameter:parmas withVC:self netName:@"司机申请加入车队" success:^(id response, NSString *msg) {
        
        [XSInfoView showInfo:@"申请成功，请等待审核" onView:weakSelf.view];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //
    if (_recordType == 1) {
        CarTeamCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.model = self.dataArray[indexPath.row];
        
        cell.teamTelButton.tag = indexPath.row + 200;
        [cell.teamTelButton addTarget:self action:@selector(telBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
    } else {
        
        CarTeamTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIDTwo"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        
        cell.model = self.dataArray[indexPath.row];
        
        cell.telButton.tag = indexPath.row + 300;
        [cell.telButton addTarget:self action:@selector(telBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
    }
    
}

- (void)cellButtonIndexClick:(NSInteger)index withButton:(UIButton *)button {
    
    WEAKSELF
    
    NSString *status = @"";
    
    NSIndexPath *indexpath = [self.tableView indexPathForRowAtPoint:[self.tableView convertPoint:button.center fromView:button.superview]];
    //    NSLog(@"点击了第%ld个item的第%ld个按钮",(long)indexpath.row, (index-99));
    
    CarTeamInvitedRecordModel *model = self.dataArray[indexpath.row];
    
    if ([button.titleLabel.text isEqual:@"同意"]) {
        status = @"1";
    } else if ([button.titleLabel.text isEqual:@"拒绝"]) {
        status = @"2";
    }
    
    NSDictionary *parmas = @{
        @"code": model.code,//邀请code
        @"status": status,//status 1-同意,2-拒绝
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
    };
    
    [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], INVITEAPPLYRECORD_AGREEORREFUSE) withParameter:parmas withVC:self netName:@"司机同意/拒绝" success:^(id response, NSString *msg) {
        
        [XSInfoView showInfo:msg onView:weakSelf.view];
        
        [weakSelf carTeamListRequest];
        
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
        //            [weakSelf.navigationController popViewControllerAnimated:YES];
        //        });
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)telBtnClick:(UIButton *)sender {
    
    if (_recordType == 1) {
        CarTeamModel *crModel = self.dataArray[sender.tag-200];
        CALL_PHONE(crModel.phone);
    } else {
        CarTeamInvitedRecordModel *model = self.dataArray[sender.tag-300];
        CALL_PHONE(model.phone);
    }
    
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_recordType == 1) {
        return cellHeight;
    } else {
        return 145;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_recordType == 1) {
        
        CarTeamModel *model = self.dataArray[indexPath.row];
        
        CarTeamCell *cell = (CarTeamCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        model.isSelected = !model.isSelected;
        
        cell.model = model;
        
        if (model.isSelected) {
            [self.carTeamCodeArray addObject:model.teamCode];
        } else {
            NSInteger index = [self.carTeamCodeArray indexOfObject:model.teamCode];
            [self.carTeamCodeArray removeObjectAtIndex:index];
        }
    }
    
}

#pragma mark - LazyLoad
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 51, ScreenW, ScreenH - NavHeight - 51 - 75);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CarTeamCell class]) bundle:nil] forCellReuseIdentifier:@"CellID"];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CarTeamTwoCell class]) bundle:nil] forCellReuseIdentifier:@"CellIDTwo"];
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (NSMutableArray *)carTeamCodeArray {
    if (!_carTeamCodeArray) {
        _carTeamCodeArray = [[NSMutableArray alloc] init];
    }
    return _carTeamCodeArray;
}
- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        _foundImageView.image = image(@"gcy_img_list_found");
        _foundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _foundImageView.center = self.view.center;
        [self.view addSubview:_foundImageView];
    }
    return _foundImageView;
}

- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setTitle:@"确认" forState:UIControlStateNormal];
        [_confirmButton setBackgroundColor:Theme_ColorValue];
        cut(_confirmButton, BTN_BORDER_RADIUS);
        [_confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _confirmButton.frame = CGRectMake(20, ScreenH - NavHeight - 65, ScreenW-40, 45);
    }
    return _confirmButton;
}

@end
